#include <stdio.h>

#include "nuclei_sdk_hal.h"



uint8_t spi_transmit_receive(uint8_t tx)
{
    QSPI_TXDATA(QSPI)=tx;
    while(QSPI_STATUS(QSPI) & (1<<0));
    return QSPI_RXDATA(QSPI) & 0xff;
}

int main(){
    int i=0;
    printf("test start\r\n");
    /*config SCK CPOL and CPHA*/
    qspi_sckmode_cfg(QSPI,~(QSPI_SCKMODE_PHA|QSPI_SCKMODE_POL));    // 00: CPOL=0,CPHA=0;
    /*disable flashxip mode*/
    qspi_fctrl_flashxip_disable(QSPI);
    /*config SCK frequency divider*/
    qspi_sckdiv_cfg(QSPI,0x01);     // SCK config: f_sck = f_clk / (2*(div+1)) = f_clk / 4;
    /*config CSMODE as HOLD*/
    qspi_csmode_cfg(QSPI,SPI_HOLD);

    printf("QSPI_SCMODE(QSPI)=0x%x\r\n",QSPI_SCMODE(QSPI));

    /*CS enable signal can be restored to default value. (4 modes exit active status.)
    * mode 1: SPI_CSID reg is written to a new and different value;
    * mode 2: SPI_CSMODE reg is written to a new and different value;
    * mode 3: SPI_CSDEF reg is written to a new and different value;
    * mode 4: SPI_FCTRL reg is set to 1;
    */
    // mode 1
    for( i = 1;i<4;i++)
    {
        QSPI_REG(SPI_REG_CSID)=0x1;
        spi_transmit_receive(i);    
        QSPI_REG(SPI_REG_CSID)=0x0;
    }
    // mode 2
    for( i = 1;i<4;i++)
    {
        QSPI_REG(SPI_REG_CSMODE)=0x2;
        spi_transmit_receive(i);
        QSPI_REG(SPI_REG_CSMODE)=0x1;
    }
    // mode 3
    for( i = 1;i<4;i++)
    {
        QSPI_REG(SPI_REG_CSDEF) &=~(0x1);
        spi_transmit_receive(i);
        QSPI_REG(SPI_REG_CSDEF)|=0x01;
    }
    // mode 4
    for( i = 1;i<4;i++)
    {
        QSPI_REG(SPI_REG_FCTRL) &=~(0x1);
        spi_transmit_receive(i);
        QSPI_REG(SPI_REG_FCTRL)|=0x01;
    }
    #ifdef CFG_SIMULATION
        pass_fail_simulation(1);
    #endif 
    printf("test finish\r\n");

    while(1);
}